package top.cyuw.simplerpc.compress.gzip;

import top.cyuw.simplerpc.compress.Compress;
import top.cyuw.simplerpc.constant.RpcConfigKeyConstants;
import top.cyuw.simplerpc.context.RpcContext;
import top.cyuw.simplerpc.exception.RpcException;
import top.cyuw.simplerpc.util.ArrayUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author chen
 * @date 2023/3/12 21:07
 */
public class GzipCompress implements Compress {

    private static final byte[] EMPTY = new byte[0];

    @Override
    public byte[] compress(byte[] bytes) {
        if (ArrayUtils.isEmpty(bytes)) {
            return EMPTY;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPOutputStream stream = new GZIPOutputStream(out);
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {
            throw new RpcException("compress failed: " + e.getMessage(), e);
        }
        return out.toByteArray();
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        if (ArrayUtils.isEmpty(bytes)) {
            return EMPTY;
        }
        int bufferSize = RpcContext.getInstance()
                .getRpcConfig().getInteger(RpcConfigKeyConstants.COMPRESS_GZIP_BUFFER_SIZE);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPInputStream stream = new GZIPInputStream(new ByteArrayInputStream(bytes));
            byte[] buffer = new byte[bufferSize];
            int n;
            while ((n = stream.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            throw new RpcException("decompress failed: " + e.getMessage(), e);
        }
        return out.toByteArray();
    }

}
